package com.eugenema.util;

import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import java.io.File;
import java.io.RandomAccessFile;
import java.util.concurrent.TimeUnit;

/**
 * 日志文件监听
 *
 * @author Eugenema
 * @date 2023/4/8 10:12
 */
public class LoggerListener {
    /** 文件变化监听器 */
    private static FileAlterationMonitor monitor;

    /**
     * 监听 info.log 日志
     *
     * @author Eugenema
     * @date 2023/4/8 10:13
     *
     **/
    public static void runMonitor() throws Exception {
        //轮询间隔
        long interval = TimeUnit.SECONDS.toMillis(1);
        //创建过滤器
        IOFileFilter filter = FileFilterUtils.and(
                // 只监听文件
                FileFilterUtils.fileFileFilter(),
                // 只监听文件后缀为info.log的文件
                FileFilterUtils.suffixFileFilter("info.log"));
        //使用过滤器
        FileAlterationObserver observer = new FileAlterationObserver(new File(ConfigUtil.LOGGER_FILE_PATH), filter);
        observer.addListener(new FileListener(new RandomAccessFile(new File(ConfigUtil.LOGGER_FILE_PATH + "info.log"), "rw").length()));
        //创建文件变化监听器
        monitor = new FileAlterationMonitor(interval, observer);
        //开始监控
        monitor.start();
    }

    /**
     * 停止文件监听
     *
     * @author Eugenema
     * @date 2023/4/8 10:15
     *
     **/
    public static void stopMonitor() {
        try {
            if (monitor == null) {
                return;
            }
            monitor.stop();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}
